package com.baizan.daka.help

import android.Manifest
import android.app.Activity
import android.app.AlertDialog
import android.app.Dialog
import android.content.Intent
import android.content.pm.ActivityInfo
import android.net.Uri
import android.os.Build
import android.util.Log
import androidx.annotation.NonNull
import androidx.core.content.FileProvider
import com.baizan.daka.Constants
import com.baizan.daka.ui.dialog.ButtomDialog
import com.baizan.daka.util.AppUtils
import com.baizan.daka.util.GifSizeFilter
import com.baizan.daka.util.PermissionDialogUtils
import com.dianzan.daka.R
import com.tbruyelle.rxpermissions.RxPermissions
import com.zhihu.matisse.Matisse
import com.zhihu.matisse.MimeType
import com.zhihu.matisse.engine.impl.GlideEngine
import com.zhihu.matisse.filter.Filter
import com.zhihu.matisse.internal.entity.CaptureStrategy
import com.zhihu.matisse.listener.OnCheckedListener
import com.zhihu.matisse.listener.OnSelectedListener
import rx.Observable
import rx.functions.Action1
import java.io.File
import java.net.URI
import java.util.*

class ImgSelectHelp {

    companion object {
        val CODE_GALLERY_REQUEST = 0x001
        val CODE_CAMERA_REQUEST = 0x002
        val CODE_RESULT_REQUEST = 0x003
    }

    private var fileUri: File? = null
    private var imageUri: Uri? = null
    private var cropImageUri: Uri? = null
    var mDialog: AlertDialog? = null
    var mContext: Activity
    var selectDialog: Dialog? = null
    var output_X = 480
    var output_Y: Int = 480
    var mPicCallback: ImgSelectHelp.PicCallback? = null
    private var selectPicCount = 6
    private var isCropImage = true //是否剪切图图片
    var files: MutableList<String>? = null

    constructor(context: Activity) {
        this.mContext = context
        checkImageDir()
    }

    private fun checkImageDir() {
        try {
            val cropedImageDir: String = Constants.DIR_PIC
            val dir = File(cropedImageDir)
            if (!dir.isDirectory) {
                dir.mkdirs()
            }
        } catch (e: Exception) {
            e.printStackTrace()
        }
    }

    fun createDialog(): Dialog {
        val pictureSelectionStr: Array<String> = arrayOf("拍照", "从手机相册选择")
        val builder: ButtomDialog.Builder = ButtomDialog.Builder(mContext)
        builder.setContentData(pictureSelectionStr)
        builder.setListener(object : ButtomDialog.OnItemSelectListener {

            override fun OnItemSelected(dialog: Dialog, position: Int, title: String?) {
                when (position) {
                    0 -> toTakingPictures()
                    1 -> multiSelectPic()
                    2 -> dialog.dismiss()
                }
            }
        })
        val dialog = builder.Build()
        selectDialog = dialog
        return dialog
    }

    fun dismiss() {
        selectDialog?.let {
            if (it.isShowing) {
                it.dismiss()
            }
        }
    }

    fun toTakingPictures() {
        val rxPermissions = RxPermissions(mContext)
        rxPermissions.request(
                Manifest.permission.CAMERA,
                Manifest.permission.WRITE_EXTERNAL_STORAGE,
                Manifest.permission.READ_EXTERNAL_STORAGE
            ) //这里填写所需要的权限
            .subscribe(Action1 {
                if (it) {
                    // 用户允许权限
                    val fileUri = File("${Constants.DIR_PIC}/${System.currentTimeMillis()}.jpg")
                    this.fileUri = fileUri
                    imageUri = Uri.fromFile(fileUri)
                    if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.N) {
                        //通过FileProvider创建一个content类型的Uri
                        imageUri =
                            FileProvider.getUriForFile(mContext, Constants.MY_PROVIDER, fileUri)
                    }
                    AppUtils.takePicture(mContext,imageUri,CODE_CAMERA_REQUEST
                    )
                } else {
                    //只要有一个权限禁止，返回false，
                    //下一次申请只申请没通过申请的权限
                    if (mDialog == null) {
                        mDialog = PermissionDialogUtils().showMyDialog(
                            mContext,
                            "进入权限设置界面开启-拍照权限和存储权限"
                        )
                    }
                    var isShow = !(mDialog?.isShowing() as Boolean)
                    if (isShow) {
                        mDialog?.show()
                    }
                }
            })
    }

    fun multiSelectPic() {
        val rxPermissions2 = RxPermissions(mContext)
        Observable.just(Any())
            .compose(rxPermissions2.ensureEach(Manifest.permission.READ_EXTERNAL_STORAGE))
            .compose(rxPermissions2.ensureEach(Manifest.permission.WRITE_EXTERNAL_STORAGE))
            .subscribe { permission ->
                if (permission.granted) {
                    // 用户允许权限

                    if (isCropImage && selectPicCount == 1) {

                        AppUtils.openPic(mContext, CODE_GALLERY_REQUEST)
                    } else {
                        matisseToGetPic()
                    }
                } else if (permission.shouldShowRequestPermissionRationale) {
                    // 用户拒绝了权限申请
                } else {
                    // 用户拒绝，并且选择不再提示
                    // 可以引导用户进入权限设置界面开启权限
                    PermissionDialogUtils().showMyDialog(mContext, "进入权限设置界面开启-存储权限")
                }
            }
    }

    fun onActivityResult(requestCode: Int, resultCode: Int, data: Intent?) {
        if (resultCode == Activity.RESULT_OK) {
            when (requestCode) {
                CODE_CAMERA_REQUEST -> if (isCropImage && selectPicCount == 1) { //去剪切
                    cropImageUri = Uri.fromFile(getFileUriileCropUri())
                    AppUtils.cropImageUri(
                        mContext,
                        imageUri,
                        cropImageUri,
                        1,
                        1,
                        output_X,
                        output_Y,
                        CODE_RESULT_REQUEST
                    )
                } else {
                    val list: MutableList<String> =
                        ArrayList()
                    list.add(fileUri!!.absolutePath)
                    onImageGet(list)
                }
                CODE_GALLERY_REQUEST -> if (isCropImage && selectPicCount == 1) { //去剪切
                    cropImageUri = Uri.fromFile(getFileUriileCropUri())
                    var newUri =
                        Uri.parse(AppUtils.getPath(mContext, data!!.data))
                    if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.N) newUri =
                        FileProvider.getUriForFile(
                            mContext,Constants.MY_PROVIDER,
                            File(newUri.path)
                        )
                    AppUtils.cropImageUri(
                        mContext, newUri, cropImageUri, 1, 1, output_X,
                        output_Y, CODE_RESULT_REQUEST
                    )
                } else {
                    val list2 =
                        Matisse.obtainPathResult(data)
                    onImageGet(list2)
                }
                CODE_RESULT_REQUEST -> if (data != null) {
                    //将Uri图片转换为Bitmap
                    try {
                        val mCropImagePath =
                            File(URI(cropImageUri.toString()))
                        val list3: MutableList<String> =
                            ArrayList()
                        list3.add(mCropImagePath.absolutePath)
                        onImageGet(list3)
                    } catch (e: java.lang.Exception) {
                        e.printStackTrace()
                    }
                }
            }
        }
    }

    fun matisseToGetPic() {
        Matisse.from(mContext)
            .choose(MimeType.ofImage(), false)
            .countable(true)
            .capture(true)
            .captureStrategy(CaptureStrategy(true, Constants.MY_PROVIDER))
            .maxSelectable(selectPicCount)
            .addFilter(GifSizeFilter(320, 320, 5 * Filter.K * Filter.K))
            .gridExpectedSize(
                mContext.resources.getDimensionPixelSize(R.dimen.grid_expected_size)
            )
            .restrictOrientation(ActivityInfo.SCREEN_ORIENTATION_PORTRAIT)
            .thumbnailScale(0.85f)
            .imageEngine(GlideEngine()) // for glide-V3
            //                .imageEngine(new Glide4Engine())    // for glide-V4
            .setOnSelectedListener(object : OnSelectedListener {

                override fun onSelected(uriList: MutableList<Uri>, pathList: MutableList<String>) {
                    Log.e("onSelected", "onSelected: pathList=$pathList")
                    files = pathList

                }
            })
            .originalEnable(true)
            .maxOriginalSize(10)
            .autoHideToolbarOnSingleTap(true)
            .setOnCheckedListener(object : OnCheckedListener {

                override fun onCheck(isChecked: Boolean) {
                    // DO SOMETHING IMMEDIATELY HERE
                    Log.e("isChecked", "onCheck: isChecked=$isChecked")
                }
            })
            .theme(R.style.LouxunMatisse)
            .forResult(CODE_GALLERY_REQUEST)
    }

    private fun getFileUriileCropUri(): File? {
        return File(Constants.DIR_PIC.toString() + "/" + System.currentTimeMillis() + ".jpg")
    }

    private fun onImageGet(list: List<String>) {
        mPicCallback?.let {
            it.onFinish(list)
        }
        selectDialog?.let {
            if (it.isShowing) {
                it.dismiss()
            }
        }

    }

    fun setCropImage(cropImage: Boolean): ImgSelectHelp {
        isCropImage = cropImage
        return this
    }

    fun setSelectPicCount(selectPicCount: Int): ImgSelectHelp {
        this.selectPicCount = selectPicCount
        return this
    }

    fun setPicCallback(picCallback: PicCallback): ImgSelectHelp {       //拍照或选择图片后的操作
        mPicCallback = picCallback
        return this
    }

    interface PicCallback {
        fun onFinish(list: List<String>)
    }
}